package com.cxb.demotest.controller;

import com.documents4j.api.IConverter;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.jodconverter.DocumentConverter;
import org.jodconverter.LocalConverter;
//import com.documents4j.job.LocalConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Objects;
import java.util.UUID;

/**
 * @ClassName TestOpenoffice
 * @Description
 * @Author cxb
 * @Date 2023-6-6 10:08
 * @Version 1.0.0
 */
@Slf4j
@Controller
public class OpenofficeController {

    @Autowired
    private DocumentConverter converter;  //用于转换

//    private IConverter converter = LocalConverter.builder().build();  //用于转换

    @SneakyThrows
    @ResponseBody
    @RequestMapping("testFileView")
    public void testFileView(HttpServletResponse response) {

        // 需要转换的文件
        File file = new File("E:/资料/工作资料/test/cxb测试1.docx");

        ServletOutputStream outputStream = null;
        InputStream inputStream = null;
        try {

            // 转换之后文件生成的地址
            File newFile = new File("E:/资料/工作资料/test/tmp");
            if (! newFile.exists()) {
                newFile.mkdirs();
            }

            // 生成pdf文件保存的路径
            String saveUrl = "E:/资料/工作资料/test/tmp";
            String fileName = "cxb-test-" + UUID.randomUUID().toString().replaceAll("-", "").substring(0, 10);
            String fileType = ".pdf";
            final String newFileUrl = saveUrl + fileName + fileType;

            // 文件转化
            converter.convert(file).to(new File(newFileUrl)).execute();
//            converter.convert(docxInputStream).as(DocumentType.DOCX).to(outputStream).as(DocumentType.PDF).execute();

            // 使用response将生成的pdf以流的方式发送到前端浏览器
            outputStream = response.getOutputStream();
            // 读取文件
            inputStream = new FileInputStream(new File(newFileUrl));
            int i = IOUtils.copy(inputStream, outputStream);
            log.info("流已关闭,可预览,该文件字节大小：" + i);

        } catch (Exception e) {
            log.error("文件预览异常");
            e.printStackTrace();
        } finally {
            if (Objects.nonNull(inputStream)) {
                inputStream.close();
            }
            if (Objects.nonNull(outputStream)) {
                outputStream.close();
            }
        }
    }

}
